<?php
/*
 * @Author: Wulala
 * @Date: 2025-04-15 11:32:20
 * @LastEditTime: 2025-04-22 17:02:41
 * @LastEditors: Wulala
 * @Description: 
 * @FilePath: \exchange\app\admin\controller\mall\OrderCash.php
 * 可以输入预定的版权声明、个性签名、空行等
 */

namespace app\admin\controller\mall;

use app\common\controller\AdminController;
use app\admin\service\annotation\ControllerAnnotation;
use app\admin\service\annotation\NodeAnnotation;
use app\admin\model\MallDealLog as MallDealLogModel;
use app\admin\model\AppConfig as AppConfigModel;
use app\admin\service\ShopService;
use app\admin\service\MailerService;
use think\response\Json;
use think\facade\Db;
use app\Request;
use think\App;
use Exception;

#[ControllerAnnotation(title: 'mall_order_cash')]
class OrderCash extends AdminController
{

    private array $notes;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new \app\admin\model\MallOrderCash();
        $this->notes = $notes = $this->model->notes;
        
        $this->assign(compact('notes'));
    }

    #[NodeAnnotation(title: '列表', auth: true)]
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = $this->model->where($where)->where('appid',$request->adminUserInfo['appid']??"")->count();
            $list  = $this->model->where($where)->where('appid',$request->adminUserInfo['appid']??"")->page($page, $limit)->order($this->sort)->select()->toArray();
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    #[NodeAnnotation(title: '发货', auth: true)]
    public function send(Request $request, $id): string
    {
        $row = $this->model->find($id);
    
        empty($row) && $this->error('数据不存在');

        $appid= $row->appid;

        if ($request->isPost()) {
            $post = $request->post();
            $rule = [];
            $this->validate($post, $rule);

            // 记录交易明细表
            $AppConfig=(new AppConfigModel)->where('appid',$appid)->find();
            $app_balance=$AppConfig['balance'];//应用账户余额
            $deal_money=$row->price*1.1;//扣费金额(倍率1.1)
            if($deal_money>$app_balance){
                $this->error('应用余额不足');
            }

            // 预算限额判断
            if(!isset($post['if_confirm'])&&($deal_money>$AppConfig['need_check'])){
                $this->error('超过单笔最大交易限制,请确认审核');
            }
            
            $day_deal_money=(new MallDealLogModel)
            ->where('create_time','between',[strtotime(date('Y-m-d')),strtotime(date('Y-m-d 23:59:59'))])
            ->where('appid',$appid)
            ->where('deal_money','<',0)
            ->sum('deal_money');//今日交易金额
            if((abs($day_deal_money)+ $deal_money)>$AppConfig['day_top']){
                $this->error('超过当日交易金额限制');
            }
           
            $month_deal_money=(new MallDealLogModel)
            ->where('create_time','between',[strtotime(date('Y-m-01 00:00:00')),strtotime(date('Y-m-t 23:59:59'))])
            ->where('appid',$appid)
            ->where('deal_money','<',0)
            ->sum('deal_money');//当月交易金额
            if((abs($month_deal_money)+ $deal_money)>$AppConfig['month_top']){
                $this->error('超过当月交易金额限制');
            }

            try {
                Db::startTrans();
                
                // 保存订单表
                $save = $row->save($post);

                //保存交易日志
                $log['appid']=$appid;
                $log['order_id']=$id;
                $log['deal_no']=date('YmdHis'.rand(100000,999999));//生成订单号;
                $log['deal_money']='-'.$deal_money;
                $log['deal_balance']=$app_balance-$deal_money;//余额
                $log['deal_type_str']='现金订单';
                $log['deal_type']=3;
                $log['remark']='';
                (new MallDealLogModel)->save($log);

                // 去通知商城系统已转账
                $appid=$row->appid;
                $shop_order_no=$row->shop_order_no;
                $pay_num=$row->pay_num;
                $send_remark=$row->send_remark;
                $res=ShopService::payCash($appid,$shop_order_no,$pay_num,$send_remark);
                if(!isset($res['code'])||$res['code']!=1){
                    throw new Exception("通知商城系统失败");
                }

                // 扣除应用余额
                (new AppConfigModel)->where('appid',$appid)->setDec('balance', $deal_money);

                // 低余额预警
                if($AppConfig['if_warning']==1){
                    if((($app_balance-$deal_money)<$AppConfig['warning_price'])&&($app_balance>$AppConfig['warning_price'])){//余额低于设置的阈值
                        $address = $AppConfig['warning_email'];
                        $titie='【元积分】充值提醒';
                        $content='您在元积分平台的账户余额已不足'.$AppConfig['warning_price'].'元,请及时充值,以免影响正常使用。';
                        (new MailerService)->send($address,$titie,$content);
                    }
                }

                // 提交事务
                Db::commit();
            }catch (\Exception $e) {
                // 发生异常，回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }


}